package com.littlecar.security.config;

import com.littlecar.security.exception.CaptchaException;
import com.littlecar.security.service.CustomerDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.HashMap;
import java.util.Map;

/**
 * 描述：
 *
 * @author littlecar
 * @date 2020/2/28 15:16
 */
@Configuration
//启用方法级别安全隔离
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private CustomerDetailService customerDetailService;
    @Autowired
    private URIFilter uriFilter;

    /**
     * 密码加密
     * @return BCryptPasswordEncoder
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 自定义登录验证
     * @return AuthenticationProvider
     */
    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(customerDetailService);
        return daoAuthenticationProvider;
    }

    /**
     * 登录异常的处理
     * @return AuthenticationFailureHandler
     */
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        ExceptionMappingAuthenticationFailureHandler failureHandler = new ExceptionMappingAuthenticationFailureHandler();
        Map<String, String> failureUrlMap = new HashMap<>();
        failureUrlMap.put(BadCredentialsException.class.getName(), LoginAuthenticationFailureHandler.PASS_ERROR_URL);
        failureUrlMap.put(CaptchaException.class.getName(), LoginAuthenticationFailureHandler.CODE_ERROR_URL);
        failureUrlMap.put(AccountExpiredException.class.getName(), LoginAuthenticationFailureHandler.EXPIRED_URL);
        failureUrlMap.put(LockedException.class.getName(), LoginAuthenticationFailureHandler.LOCKED_URL);
        failureUrlMap.put(DisabledException.class.getName(), LoginAuthenticationFailureHandler.DISABLED_URL);
        failureHandler.setExceptionMappings(failureUrlMap);
        return failureHandler;
    }

    /**
     * 自定义登录过滤器
     * {@link UsernamePasswordAuthenticationFilter}
     * @return LoginAuthenticationFilter
     * @throws Exception
     */
//    public LoginAuthenticationFilter loginAuthenticationFilter() throws Exception {
////        LoginAuthenticationFilter loginAuthenticationFilter = new LoginAuthenticationFilter();
////        loginAuthenticationFilter.setAuthenticationManager(authenticationManager());
////        //登录失败
////        loginAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
////        //登录成功后可使用loginSuccessHandler()存储查询用户信息，主页跳转等，可选。
//////        loginAuthenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler());
////        //RememberMeServices
//////        loginAuthenticationFilter.setRememberMeServices(persistentTokenBasedRememberMeServices());
////        return loginAuthenticationFilter;
////    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .addFilterBefore(uriFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin()
                .loginPage("/security/login")
                .successForwardUrl("/security/loginSuccess")
                .failureUrl("/security/login")
                .loginProcessingUrl("/login-in")
                .and()
                .authorizeRequests()
                .antMatchers().permitAll()
                .anyRequest().authenticated()
                .and()
                .headers()
//                  X-Frame-Options HTTP 响应头
                .frameOptions().sameOrigin()
                .and()
                .csrf().disable();

    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers("/js/**","/css/**","/json/**","/layui/**","/images/**");
    }
    /**
     *create two users admin and user
     * 测试专用,不需要经过数据库
     * @param auth
     * @throws Exception
     * */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("user").password(new BCryptPasswordEncoder().encode("123456"))
                .and()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").password(new BCryptPasswordEncoder().encode("123456"));
    }
}
